/**
 * @section LICENSE
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details at
 * http://www.gnu.org/copyleft/gpl.html
 */

#include <SDLVideoOutput.h>

#include <iostream>
#include <stdexcept>

#include <SDL/SDL_gfxPrimitives.h>

namespace
{
	const int RETURN_SUCCESS(0);
} // end namespace anonymous

namespace BD = BlockDropper;

BD::SDLVideoOutput::SDLVideoOutput()
	: initialiser()
	, displaySurface()
{
}

BD::SDLVideoOutput::~SDLVideoOutput()
{
	SDL_Quit();
}

void BD::SDLVideoOutput::drawLine(const Point<unsigned short> & point1, 
                                  const Point<unsigned short> & point2, const Colour & colour)
{
	const int retCode(lineRGBA(displaySurface.ptr(), point1.x, point1.y, point2.x, point2.y, 
	                           colour.r, colour.g, colour.b, colour.a));

	if(retCode != RETURN_SUCCESS)
	{
		throw std::runtime_error("Drawing line failed");
	}
}

void BD::SDLVideoOutput::drawRectangle(const Rectangle & rectSrc, const Colour & colour)
{
	const unsigned rgba(SDL_MapRGBA(displaySurface.ptr()->format, 
                                  colour.r, colour.g, colour.b, colour.a));

	SDL_Rect rect = {static_cast<short>(rectSrc.left()),
                   static_cast<short>(rectSrc.top()),
                   rectSrc.width(),
                   rectSrc.height()};

  const int retCode(SDL_FillRect(displaySurface.ptr(), &rect, rgba));

	if(retCode != RETURN_SUCCESS)
	{
		throw std::runtime_error("Drawing line failed");
	}
}

unsigned short BD::SDLVideoOutput::height() const
{
	return BD::SDLDisplaySurface::height;
}

void BD::SDLVideoOutput::update()
{
	SDL_Flip(displaySurface.ptr());
}

unsigned short BD::SDLVideoOutput::width() const
{
	return BD::SDLDisplaySurface::width;
}

